package com.k8.common.ioc.injectorImpl;

import com.k8.common.ioc.Injector;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;


public class InjectorWrapper extends AbstractInstanceStrategyFactoryInjector {
    @Override
    public void synJudge(Map<String, Object> relyBeanNames) {
        for (Injector injector : injectors) {
            injector.synJudge(relyBeanNames);
        }
    }

    private List<Injector> injectors;

    public void setInjectors(List<Injector> injectors) {
        this.injectors = injectors;
    }

    @Override
    public boolean inject(Map<String, Object> relyBeanMaps, Object object, Field field) {
        for (Injector injector : injectors) {
            if (injector.needInject(field) && injector.inject(relyBeanMaps, object, field)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public boolean needInject(Field field) {
        for (Injector injector : injectors) {
            if (injector.needInject(field)) return true;
        }
        return false;
    }

    @Override
    public <T> T getBean(final Map<String, SafeObjectHolder> relyBeanMaps, Class<T> clazz, String name) {

        for (Injector injector : injectors) {
            T bean = injector.getBean(relyBeanMaps, clazz, name);
            if (bean != null) return bean;
        }
        return null;
    }

    @Override
    public <T> T getBean(final Map<String, SafeObjectHolder> relyBeanMaps, Class<T> clazz) {
        for (Injector injector : injectors) {
            T bean = injector.getBean(relyBeanMaps, clazz);
            if (bean != null) return bean;
        }
        return null;
    }

    @Override
    public <T> T getBeanOrRegistry(final Map<String, SafeObjectHolder> relyBeanMaps, Class<T> clazz, String name) {
        for (Injector injector : injectors) {
            T bean = injector.getBeanOrRegistry(relyBeanMaps, clazz, name);
            if (bean != null) return bean;
        }
        return null;
    }

    @Override
    public <T> T getBeanOrRegistry(final Map<String, SafeObjectHolder> relyBeanMaps, Class<T> clazz) {
        for (Injector injector : injectors) {
            T bean = injector.getBeanOrRegistry(relyBeanMaps, clazz);
            if (bean != null) return bean;
        }
        return null;
    }

    @Override
    public <T> List<T> getAllBeans(Map<String, SafeObjectHolder> relyBeanMaps, Class<T> clazz) {
        for (Injector injector : injectors) {
            List<T> allBeans = injector.getAllBeans(relyBeanMaps, clazz);
            if (allBeans != null && !allBeans.isEmpty()) return allBeans;
        }
        return null;
    }

    @Override
    public <T> T getAdaptive(Map<String, SafeObjectHolder> relyBeanMaps, Class<T> clazz) {
        for (Injector injector : injectors) {
            T adaptive = injector.getAdaptive(relyBeanMaps, clazz);
            if (adaptive != null) return adaptive;
        }
        return null;
    }
}
